package com.example.springboot1.file;

/**
 * @author ckj
 * @description TODO
 * @date 2023-03-14 11:19
 */


import com.google.common.base.Stopwatch;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.OptionalLong;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.LongAdder;

public class LargeFileV {
    public static void main(String[] args) throws IOException {
        String fileName = "E:/numbers.txt";
        long l = System.currentTimeMillis();

        LongAdder count = new LongAdder();
        LongAdder sum = new LongAdder();
        final OptionalLong[] max = {OptionalLong.empty()};
        final OptionalLong[] min = {OptionalLong.empty()};
        Stopwatch stopwatch = Stopwatch.createStarted();
        Files.lines(Paths.get(fileName))
                .parallel()
                .flatMap(line -> Arrays.stream(line.split(",")))
                .mapToLong(Long::parseLong)
                .forEach(num -> {
                    count.increment();
                    sum.add(num);
                    max[0] = max[0].isPresent() ? OptionalLong.of(Math.max(max[0].getAsLong(), num)) : OptionalLong.of(num);
                    min[0] = min[0].isPresent() ? OptionalLong.of(Math.min(min[0].getAsLong(), num)) : OptionalLong.of(num);
                });

        double avg = (double) sum.sum() / count.sum();
        System.out.println("Count: " + count.sum());
        System.out.println("Sum: " + sum.sum());
        System.out.println("Average: " + avg);
        System.out.println("Max: " + max[0].getAsLong());
        System.out.println("Min: " + min[0].getAsLong());
        System.out.println("普通读取资源结束,获取了" + count + "行,用时" + stopwatch.elapsed(TimeUnit.SECONDS) + "s");
    }
}

